<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowd');

class File_manipulate {

    function __construct() {
        
    }

    function _upload($param) {
        //name, 
        extract($param);
        $ret = array('error' => FALSE);

        $config['upload_path'] = UPLOADS_DIR;
        //$config['allowed_types'] = (isset ($allowed_types))?$allowed_types:'gif|jpg|png';
        $config['encrypt_name'] = TRUE;
        $config['overwrite'] = TRUE;

        //$config['max_size'] = '100';
        //$config['max_width'] = '1024';
        //$config['max_height'] = '768';

        if (isset($path)) {
            $config['upload_path'] = $config['upload_path'] . $path . '/';
            $this->create_dir($path);
        }

        if (isset($file_name)) {
            $config['encrypt_name'] = FALSE;
            $config['file_name'] = $file_name;
        }

        //$real_file = $config['upload_path'] . $config['file_name'];

        $CI = & get_instance();
        $CI->load->library('upload', $config);

        if (!$CI->upload->do_upload($name)) {
            $ret['error'] = $CI->upload->display_errors();
        } else {
            $data = $CI->upload->data();
            unset($ret['error']);
            $ret = $data;

            /* if (isset($resize)) {

              $ret['error'] = $this->img_resize(array('new_image'=>$real_file,'source_image'=>$real_file));
              p($ret.$resize.$real_file.'--this',true);
              } */
        }
        return $ret;
    }

    public function img_resize($param) {
        extract($param);
        if (isset($new_image)) {
            $new_image = UPLOADS_DIR . $path . '/' . $new_image;
            $config['new_image'] = $new_image;
            $this->create_dir($path);
        }

        $ret = array('error' => FALSE);

        //$config['image_library'] = 'gd2';
        $config['image_library'] = 'GD2';
        $config['source_image'] = $source_image;
        
        $config['maintain_ratio'] = (isset($width)&&isset($height))?FALSE:TRUE;

        $config['width'] = (isset($width)) ? $width : 376;
        $config['height'] = (isset($height)) ? $height : 281;
        $config['quality'] = '80%';
        
        $config['dynamic_output'] = (isset($new_image)) ? FALSE : TRUE;
        
        $CI = & get_instance();
        $CI->load->library('image_lib', $config);

        $ret['error'] = $CI->image_lib->resize();

        if (!$ret['error']) {
            $ret['error'] = $CI->image_lib->display_errors();
        } else {
            (!isset($show)) ? $ret['error'] = false : "";
        }

        unset($config);
        $CI->image_lib->clear();

        return $ret['error'];
    }
    
    function upload($user, $id = 0){
        $data = array();
        $name = '';
        $CI = & get_instance();
        if($_FILES){
            foreach ($_FILES as $i => $v){

               foreach ($v as $i2 => $v2){
                   $v[$i2] = str_replace(' ', '_', $v2);
               }

               $extension = $this->get_extension($v['name']);
               
               $res = $this->validate_file($extension);
               
                   
               
               if($res['is_valid']){
                   
                   $new_name = uniqid() . '.' . $extension;
                   
                   $upload_path = $user.'/'.$res['type'].'/';

                   $this->create_dir($upload_path);

                   $real_file = UPLOADS_DIR . $upload_path . $new_name;
                   
                   move_uploaded_file($v['tmp_name'], $real_file);
                   
                   if($res['type'] == 'picture'){
                       $thumbnail_path = $user . '/thumbnail/';
                       $v['thumbnail'] = 'uploads/' . $thumbnail_path . $new_name;
                       $param = array(
                            'source_image' => $real_file,
                            'height' => 45,
                            'new_image' => $new_name,
                            'path' => $thumbnail_path,
                       );
                       $this->img_resize($param);
                   }
                   
                   $v['type'] = $res['type'];
                   $v['location'] = str_replace(DOC_ROOT, '', $real_file);
                   $v['user'] = $user;
                   
                   if($id){
                       $CI->qb->delete_file(array('from'=>'files','field'=>'id','key'=>$id));
                       $CI->db->where('id', $id);
                       $CI->db->update('files',$v);
                   }else{
                       $CI->db->insert('files',  $v);
                       $id = $CI->qb->get_last_id('files');
                   }

               }
            }
        }
            
        return $id;
    }
    
    function create_dir($path) {
        $a_path = explode("/", $path);
        $con_path = UPLOADS_DIR;
        foreach ($a_path as $d) {
            $con_path.=$d . '/';
            if ($d && !file_exists($con_path)) {
                mkdir($con_path, 0777);
            }
        }
    }
    
    function get_extension($string) {
        $array = explode('.', $string);
        return $array[count($array) - 1];
    }
    
    function validate_file($extension) {
        $ret = array('type'=>'', 'is_valid'=>false);
        
        $array = array(
            'picture'=>array('png', 'gif', 'jpg'),
            'document'=>array('txt', 'rtf', 'doc')
        );
        
        foreach ($array as $i => $v) {
            
            foreach ($v as $v2){
                if ($extension == $v2 || $extension == strtoupper($v2)) {
                    $ret['type'] = $i;
                    $ret['is_valid']=true;
                    break;
                }
            }
            if($ret['is_valid'])break;
                
        }
        return $ret;
    }

    

}

